# -*- coding: utf-8  -*-
#    Copyright (C) 2009 Osama Khalid
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
import wikipedia, okbot, cPickle, time

class exif:
  def __init__(self):
    self.site = wikipedia.getSite(fam='commons', code='commons')
    self.filesError = open('fileserror.txt','a')
    try:
      self.doneFiles = cPickle.load(open('./donedfiles.db','r'))
    except IOError:
      self.doneFiles = set()

  def run(self):
    categoryFiles = self.getCategory('Category:Pictures by James Lindsey')
    
    for categoryFile in (set(categoryFiles) - self.doneFiles):
      fileInfo = self.getInfo(categoryFile)
      if fileInfo == None: #if there were any problem with fileInfo, report it and skip.
        self.filesError.write(categoryFile + '\n')
        continue
      self.putInfo(self.getInfo(categoryFile), categoryFile)
      self.doneFiles.add(categoryFile)
      cPickle.dump(self.doneFiles, open('./donedfiles.db','w'))
      time.sleep(10)

  def getInfo(self, categoryFile):
    predata = {#api.php?action=query&titles=File:Acer.platanoides.-.lindsey.jpg&prop=imageinfo&iiprop=metadata&format=jsonfm
             'action': 'query',
             'titles': categoryFile,
             'prop': 'imageinfo',
             'iiprop': 'metadata',
             'format': 'json',
              }
    while True:
      fileData = okbot.getAPI(self.site, predata)
      if fileData != None: break
    try: #First, check if 'DateTimeOriginal' is available, if it isn't look for 'DateTime'.
      for date in [metadata for metadata in fileData['query']['pages'].values()[0]['imageinfo'][0]['metadata'] if metadata['name'] == 'DateTimeOriginal']: 
        dateTaken = time.strftime("%Y-%m-%d", time.strptime(date['value'], '%Y:%m:%d %H:%M:%S')) # Converting to a 'human-readable' form.
        print dateTaken #For debugging.
        return dateTaken
      for date in [metadata for metadata in fileData['query']['pages'].values()[0]['imageinfo'][0]['metadata'] if metadata['name'] == 'DateTime']:
        dateTaken = time.strftime("%Y-%m-%d", time.strptime(date['value'], '%Y:%m:%d %H:%M:%S')) # Converting to a 'human-readable' form.
        print dateTaken #For debugging.
        return dateTaken
    except:
      print "Problem with " + categoryFile
    print "Got nothing!"
    print categoryFile

  def putInfo(self, date, categoryFile):
    filePage = wikipedia.Page(self.site, categoryFile)
    filePageText = filePage.get()

    replaceText = filePageText[filePageText.find('Date='): filePageText.find('Date=') + filePageText[filePageText.find('Date='):].find('|')].rstrip('\n')
    filePageText = filePageText.replace(replaceText, 'Date= ' + date)

    okbot.put_page(self.site, filePage, filePageText, u'Robot: Adding the date from the metadata')

  def getCategory(self, categoryName):
    cmcontinue = '!|'
    categoryItems = list()

    print "Getting %s items" % categoryName
    while cmcontinue:
      predata = {#api.php?action=query&list=categorymembers&cmtitle=Category:User-created_public_domain_images&cmnamespace=6&cmcontinue=Shervin|&cmlimit=50&format=jsonfm
               'action': 'query',
               'list': 'categorymembers',
               'cmtitle': categoryName,
               'cmcontinue': cmcontinue,
               'cmprop': 'title',
               'cmlimit': '500',
               'format': 'json',
                }

      while True:
        categoryData = okbot.getAPI(self.site, predata)
        if categoryData != None: break

      for page in categoryData['query']['categorymembers']:
        categoryItems.append(page['title'])

      if 'query-continue' in categoryData:
        cmcontinue = categoryData['query-continue']['categorymembers']['cmcontinue']
      else: # If there is no more items in the category
        cmcontinue = False
    return categoryItems

if __name__ == '__main__':
  try:
    bot = exif()
    bot.run()
  finally:
    wikipedia.stopme()
